package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.CheckGroupDao;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.result.PageResult;
import com.itheima.health.result.QueryPageBean;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    /**
     * 套餐新增
     * @param setmeal
     * @param checkGroupIds
     */
    @Transactional
    public void add(Setmeal setmeal, List<Integer> checkGroupIds) {
        setmealDao.insert(setmeal);
        setSetmealAndCheckGroup(setmeal,checkGroupIds);
    }

    /**
     * 将检查组添加进套餐中
     * @param setmeal
     * @param checkGroupIds
     */
    private void setSetmealAndCheckGroup(Setmeal setmeal, List<Integer> checkGroupIds) {
        if (!CollectionUtils.isEmpty(checkGroupIds)) {
            for (Integer checkGroupId : checkGroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("checkGroupId", checkGroupId);
                map.put("setmealId", setmeal.getId());
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

    /**
     * 套餐分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 查询所有的套餐
     * @return
     */
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    /**
     * 根据id查询套餐信息
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }
}
